/*
    config.c
    Achieve the config moudle
    BeginnerC
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* 
    GetConfigValue
        Get the value to the key
    Argument
        config
            The pointer to the config
        key
            The key want to search
    Return Value
        If found, return the pointer to the buffer
        Else, return the NULL
*/
char* GetConfigValue(Config *config, const char *key)
{
    while (config)
    {
        if (*(config -> key) == '\0')
        {
            break;
        }
        if (!strcmp(config -> key, key))
            return config -> value;
        config++;
    }
    return NULL;
}
/* 
    FreeConfig
        Free config memory
    Argument
        config
            The pointer to the config
    Return Value
        No value will return
*/
void FreeConfig(Config *config)
{
    free(config);
}
/* 
    LoadConfig
        Load config
    Arguement
        config_path
            The config file path
    Return Value
        The pointer to the config
        If failed, return NULL
*/
Config* LoadConfig(const char *config_path)
{
    Config *result = NULL;
    FILE *fp = NULL;
    int count_line = 0;
    char buffer[LINE_MAX_LENGTH] = {};
    fp = fopen(config_path, "r");
    if (NULL == fp)
    {
        return NULL;
    }
    while (!feof(fp))
    {
        fgets(buffer, LINE_MAX_LENGTH, fp);
        if (*buffer == '\n')
        {
            break;
        }
        count_line++;
    }
    if (0 >= count_line)
    {
        fclose(fp);
        return NULL;
    }
    result = calloc(count_line + 1, sizeof(Config));
    if (NULL == result)
    {
        fclose(fp);
        return NULL;
    }
    rewind(fp);
    for (int i = 0;!feof(fp);i++)
    {
        char *position = NULL, *temp = NULL;
        fgets(buffer, LINE_MAX_LENGTH, fp);
        if (*buffer == '\n')
        {
            break;
        }
        position = strchr(buffer, '=');
        temp = position;
        if (*(position - 1) == ' ')
        {
            position--;
            while (*(position - 1) == ' ')
            {
                position--;
            }
        }
        memcpy(result[i].key, buffer, position - buffer);
        position = temp;
        position++;
        if (*position == ' ')
        {
            position++;
            while (*position == ' ')
            {
                position++;
            }
        }
        for (int j = 0;*(position + j) && *(position + j) != '\n';j++)
        {
            result[i].value[j] = *(position + j);
        }
    }
    fclose(fp);
    return result;
}